<?php
namespace app\api\controller\deerhome\user;

use app\api\controller\deerhome\user\BaseAuth;
use think\Db;
use think\Validate;
use OSS\OssClient;
/**
 * 分销中心
 */
class Agent extends BaseAuth
{
    /**
     * 收支明细
     */
    public function log()
    {
        $month=$this->request->param("month","",'trim');
        $cate=$this->request->param("cate",0,'intval');
        $where=[];
        $where['deerhome_user_id']=$this->_user['id'];
        if($cate==1){
            $where['type']="分销提现";
            $where['status']="1";
        }
        if($cate==2){
            $where['type']="分销提现";
            $where['status']="2";
        }
        if(preg_match("/^\d{4}-\d{2}$/",$month)){
            $where['addtime']=['like',$month.'%'];
        }
        $data=Db::name("deerhome_worker_money_log")->where($where)->order("id desc")->paginate(10)->each(function($item, $key){
            $item['time']=date("m-d H:i",strtotime($item['addtime']));
            if($item['type']=="服务分成"){
                $item['note']="#".$item['jz_order_sn'];
            }
            return $item;
        });
        $this->ok($data);
    }
    /**
     * 分销订单列表
     */
    public function orderlist()
    {
        $page=$this->request->param("page",1,'intval');
        $s=$this->request->param("s",0,'intval');

        \think\Lang::load(APP_PATH."admin/lang/zh-cn/deerhome/order.php");
        $orderModel = new \app\admin\model\deerhome\Order;

        $where=[];
        
        $where['o.status']=["in",[2,3,4,5]];
        $where['o.agent_lev1_uid|o.agent_lev2_uid']=$this->_user['id'];
        
        if($s==2){
            $where['o.agent_lev1_price_js|o.agent_lev2_price_js']=2;
        }
        $data=Db::name("deerhome_order")->alias("o")
        ->join("deerhome_items i","i.id=o.jz_items_id","left")
        ->field("o.*,i.face_image")
        ->where($where)
        ->order("o.id desc")->paginate(6)->each(function($item,$key)use($orderModel){
            $item['status_txt']=$orderModel->getStatusTextAttr($item['status'],$item);
            $item['status_pay']="未入账";
            if($item['agent_lev1_price_js']==1){$item['status_pay']="已入账";}
            $item['user_phone']=substr($item['user_phone'],0,3)."****".substr($item['user_phone'],7,4);
            $item['price_fy']="";
            if($this->_user['id']==$item['agent_lev1_uid']){
                $item['price_fy']="一级推广费￥".number_format($item['agent_lev1_price'],2);
            }
            if($this->_user['id']==$item['agent_lev2_uid']){
                $item['price_fy']="二级推广费￥".number_format($item['agent_lev2_price'],2);
            }
            return $item;
        });
        $this->ok($data);
    }
    /**
     * 下级用户列表
     */
    public function userlist()
    {
        $list=Db::name("deerhome_user")->where("agent_lev1_uid",$this->_user['id'])
        ->field("id,face_image,regtime,uname")
        ->order("id desc")->paginate(10)->each(function($item,$key){
            $item['regtime']=date("m-d H:i",strtotime($item['regtime']));
            $item['ds']='0';
            $item['xf']='0';
            $item['tag']='UID'.$item['id'];
            $xf=Db::name("deerhome_order")->where("jz_user_id",$item['id'])->where("agent_lev1_uid|agent_lev2_uid",$this->_user['id'])->where("status","in",[2,3,4,5])->field("sum(price_payed) as xf,count(id) as ds")->find();
            if($xf){
                $item['xf']=$xf['xf'];
                $item['ds']=$xf['ds'];
            }
            $item['xf']=number_format($item['xf'],2);
            return $item;
        });

        $this->ok($list);
    }
    /**
     * 分销中心首页
    */
    public function index()
    {
        $data=[];
        $data['rule']="";
        $data['bg']=$this->fixImg("/assets/addons/deerhome/img/lev_bg.png");
        $data['lev']="新手";
        if($this->_user['agent_lev_id']>0){
            $levData=Db::name("deerhome_agent_lev")->where("id",$this->_user['agent_lev_id'])->find();
            if($levData){
                $data['lev']=$levData['name'];
                if($levData['bg_image']){
                    $data['bg']=$levData['bg_image'];
                }
            }
        }
        $data['username']=$this->_user['uname'];
        $data['userface']=$this->_user['face_image'];
        $data['money_left']=$this->_user['wallet_left'];

        //待入账
        $data['money_onway']=0;
        //累计佣金
        $data['money_total']=0;
        $money_onwayArr=Db::name("deerhome_order")->where("agent_lev1_uid|agent_lev2_uid",$this->_user['id'])->where("status","in",[2,3,4,5])->where("agent_lev1_price",">",0)->field("agent_lev2_price_js,agent_lev1_price_js,agent_lev1_uid,agent_lev2_uid,agent_lev1_price,agent_lev2_price")->select();
        foreach ($money_onwayArr as $key => $value) {
            if($value['agent_lev1_uid']==$this->_user['id']){
                $data['money_total']=bcadd($data['money_total'],$value['agent_lev1_price'],2);
                if($value['agent_lev1_price_js']==2){
                    $data['money_onway']=bcadd($data['money_onway'],$value['agent_lev1_price'],2);
                }
            }
            if($value['agent_lev2_uid']==$this->_user['id']){
                $data['money_total']=bcadd($data['money_total'],$value['agent_lev2_price'],2);
                if($value['agent_lev2_price_js']==2){
                    $data['money_onway']=bcadd($data['money_onway'],$value['agent_lev2_price'],2);
                }
            }
        }
        $data['money_onway']=number_format($data['money_onway'],2);
        $data['money_total']=number_format($data['money_total'],2);

        //提现中
        $data['money_ing']=Db::name("deerhome_worker_money_log")->where("deerhome_user_id",$this->_user['id'])->where("type","分销提现")->where("status",1)->sum("price");
        if($data['money_ing']<0){
            $data['money_ing']*=-1;
        }
        $data['money_ing']=number_format($data['money_ing'],2);

        //已提现
        $data['money_geted']=Db::name("deerhome_worker_money_log")->where("deerhome_user_id",$this->_user['id'])->where("type","分销提现")->where("status",2)->sum("price");
        if($data['money_geted']<0){
            $data['money_geted']*=-1;
        }
        $data['money_geted']=number_format($data['money_geted'],2);

        //推广人数
        $data['users']=Db::name("deerhome_user")->where("agent_lev1_uid",$this->_user['id'])->count();
        $data['users']=number_format($data['users'],0);

        //推广订单
        $data['order']=Db::name("deerhome_order")->where('status','in',[2,3,4,5])->where("agent_lev1_uid|agent_lev2_uid",$this->_user['id'])->where("agent_lev1_price",">",0)->count();
        $data['order']=number_format($data['order'],0);

        //银行卡信息
        $data['card_info']="未添加";
        $user_card=Db::name("deerhome_worker_card")->where("deerhome_user_id",$this->_user['id'])->find();
        if($user_card){
            $data['card_info']="{$user_card['bank']} ".substr($user_card['card'],-4);
        }

        $this->xcxLog("分销中心");
        $this->ok($data);
    }
    /**
     * 查询余额
    */
    public function price(){
        $data=[];
        $data['money_left']=$this->_user['wallet_left'];
        $data['min_money']=\Tools\Config::getAgentTxMinMoney();
        $this->ok($data);
    }
    /**
     * 提现申请
    */
    public function add(){
        $price=$this->request->param("price",0,'floatval');
        if($price<=0){
            $this->err("请输入正确的金额");
        }
        if(\bccomp($price, $this->_user['wallet_left'],2)==1){
            $this->err("余额不足");
        }
        $minMoney=\Tools\Config::getAgentTxMinMoney();
        if(\bccomp($price, $minMoney,2)==-1){
            $this->err("最低提现金额为{$minMoney}元");
        }
        $user_card=Db::name("deerhome_worker_card")->where("deerhome_user_id",$this->_user['id'])->find();
        if(!$user_card){
            $this->err("请先填写银行卡信息");
        }
        Db::startTrans();
        try{
            Db::name("deerhome_worker_money_log")->insert([
                'type'=>"分销提现",
                'deerhome_user_id'=>$this->_user['id'],
                'price'=>$price*-1,
                'skr'=>$user_card['uname'],
                'bank'=>$user_card['bank'],
                'bankcard'=>$user_card['card'],
                'note'=>"申请提现，等待处理",
                'addtime'=>date("Y-m-d H:i:s")
            ]);
            Db::name("deerhome_user")->where("id",$this->_user['id'])->setDec("wallet_left",$price);
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $this->err($e->getMessage());
        }
        $this->ok();
    }
    /**
     * 二维码
    */
    public function getcode()
    {
        $this->xcxLog("推广海报");
        $data=[];
        $qr=$this->creatQrcode();
        $data['imgs']=$this->creatPoster($qr);
        $data['imgs']=array_filter($data['imgs']);
        $data['imgs'][]=$this->fixImg($qr);
        $this->ok($data);
    }
    /**
     * 合成海报图
    */
    private function creatPoster($qr){
        $bgImgs=\Tools\Config::getAgentPostBgImg();
        $diyBg=$this->_user['agent_qr_diy_bg'];
        if(count($bgImgs)==0 && $diyBg==""){
            return [];
        }
        if($diyBg){
            array_unshift($bgImgs,$diyBg);
        }
        $qr=APP_PATH."../public".$qr;
        foreach ($bgImgs as &$val) {
            $key=md5($val);
            $outputPath = "/uploads/u{$this->_user['id']}_{$key}.jpg";
            if(file_exists(APP_PATH."../public".$outputPath)){
                $val=$outputPath;
                continue;
            }
            $bgPath=APP_PATH."../public/".$val;
            if(!file_exists($bgPath)){
                continue;
            }
            list($width_bg, $height_bg,$imgType) = getimagesize($bgPath);
        
            if($imgType==IMAGETYPE_PNG){
                $background = imagecreatefrompng($bgPath);
            }else{
                $background = imagecreatefromjpeg($bgPath);
            }
            $foreground = imagecreatefromjpeg($qr);
            
            $width=180;
            $height=180;
            $x = $width_bg/2-$width/2;
            $y = $height_bg-$height-70;
            $foreground = imagescale($foreground, $width, $height);
            imagecopy($background, $foreground, $x, $y, 0, 0, $width, $height);
            
            imagejpeg($background, APP_PATH."../public".$outputPath, 80);

            $val=$outputPath;
        }
        foreach ($bgImgs as &$bg) {
            $bg=$this->fixImg($bg)."?".time();
        }
        return $bgImgs;
    }
   
    /**
     * 生成小程序码
    */
    private function creatQrcode(){
        if($this->_user['agent_qr']){
            return $this->_user['agent_qr'];
        }
        $fileName="u{$this->_user['id']}_qr.png";
        $filePath= APP_PATH ."../public/uploads/".$fileName;
        $imgUrl="/uploads/{$fileName}";
        $img="";
        try{
            $configWx=$this->getWeixinConfig();
            $Qrcode = \WeMini\Qrcode::instance($configWx);
            $query="/pages/index/index?wxid={$this->_user['wxid']}";
            $img = $Qrcode->createMiniPath($query);
            file_put_contents($filePath,$img);
        }catch(\Exception $e){
            $this->err($e->getMessage());
        }
        $cdnurl=$this->fixImg($imgUrl);
        Db::name("deerhome_user")->where("id",$this->_user['id'])->update(['agent_qr'=>$imgUrl]);
        return $imgUrl;
    }
    /**
     * 银行卡信息
    */
    public function card()
    {
        $data=[];
        $data['uname']=$this->_user['uname'];
        $data['list']=Db::name("deerhome_bank")->where("status",1)->column("bank");
        $data['bank']="";
        $data['card']="";

        $has=Db::name("deerhome_worker_card")->where("deerhome_user_id",$this->_user['id'])->find();
        if($has){
            $data['uname']=$has['uname'];
            $data['bank']=$has['bank'];
            $data['card']=$has['card'];
        }
       
        $this->ok($data);
    }
    /**
     * 添加银行卡信息
    */
    public function add_card(){
        $bankTip=$this->request->param("bankTip","",'trim');
        $card=$this->request->param("card","",'trim');
        if($bankTip==""){
            $this->err("请选择银行");
        }
        if(!preg_match("/^\d{10,19}$/",$card)){
            $this->err("请输入正确的银行卡号");
        }
        $isExist=Db::name("deerhome_bank")->where("status",1)->where("bank",$bankTip)->find();
        if(!$isExist){
            $this->err("银行不存在");
        }
        $has=Db::name("deerhome_worker_card")->where("deerhome_user_id",$this->_user['id'])->find();
        if($has){
            $this->err("已经绑定过银行卡");
        }
        Db::name("deerhome_worker_card")->insert([
            "jz_worker_id"=>0,
            "deerhome_user_id"=>$this->_user['id'],
            "uname"=>$this->_user['uname'],
            "bank"=>$bankTip,
            "card"=>$card,
            "add_time"=>\date("Y-m-d H:i:s")
        ]);
        $this->ok();
    }
}
